<template>
  <div class="game-list-page">
    <!-- <div class="gp-filter">
      <div class="gp-img-layout">
        <DropDown :list="tList" :value.sync="queryParams.orderByColumn" :tlist="tagFilter" :subvalue.sync="queryParams.rank" @change="handleSearch()" style="min-width: 150px;" placeholder="" />
        <div class="label-filter">
          <span class="tit">平台</span>
          <div class="plat-items">
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
              <i class="sm-tip" slot-content>PC</i>
              <span slot="reference" class="pitem windows" :class="{ 'active': queryParams.device == 'PC' }"
                @click="chooseDevice('PC')"></span>
            </el-popover>
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
              <i class="sm-tip" slot-content>主机</i>
              <span slot="reference" class="pitem xbox" :class="{ 'active': queryParams.device == '主机' }"
                @click="chooseDevice('主机')"></span></el-popover>
            
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
              <i class="sm-tip" slot-content>掌机</i>
              <span slot="reference" class="pitem switch" :class="{ 'active': queryParams.device == '掌机' }"
                @click="chooseDevice('掌机')"></span></el-popover>

            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
              <i class="sm-tip" slot-content>手游</i>
              <span slot="reference" class="pitem apple" :class="{ 'active': queryParams.device == '手游' }"
                @click="chooseDevice('手游')"></span></el-popover>
          </div>
        </div>
        <div class="label-filter">
          <span class="tit">版式</span>
          <div class="plat-items">
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
              <i class="sm-tip" slot-content>横屏</i>
              <span slot="reference" class="pitem h-screen" :class="{ 'active': queryParams.orientation == '横屏' }"
                @click="chooseScreen('横屏')"></span></el-popover>
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
              <i class="sm-tip" slot-content>竖屏</i>
              <span slot="reference" class="pitem s-screen" :class="{ 'active': queryParams.orientation == '竖屏' }"
                @click="chooseScreen('竖屏')"></span></el-popover>
          </div>
        </div>
        <div class="seach-bx has-filter-scroll" :class="{'active':searchIsFocus}">
          <div class="q-f-item-wrap">
            <template v-for="c in cateObj">
              <div class="q-f-item" v-for="s in c.items" v-if="s.selected"><span class="ct">{{ c.name }}</span><span
                  class="ct-val">{{ s.title }}</span><i class="it-clr" @click="onParamterClear(c, s)"></i>
              </div>
            </template>
            <input type="text"  @focus="searchIsFocus=true" @blur="searchIsFocus=false" v-model="queryParams.title" @keypress.enter="handleSearch"
              :placeholder="'按标题/风格/类型等搜索 ' + inspirationInfo.articleNum + ' 款游戏'" /><a class="cancel-search"
              v-if="queryParams.title" @click="handleXClear"></a>
          </div>
        </div>
        <div class="bs-layout">
          <div class="plat-items">
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                <i class="sm-tip" slot-content>大图模式</i>
                  <span slot="reference" class="f-layout" :class="{'active':model=='big'}" @click="model='big'"></span>
              </el-popover>
                  <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                  <i class="sm-tip" slot-content>小图模式</i>
                  <span slot="reference" class="mup-layout" :class="{'active':model=='small'}" @click="model='small'"></span>
              </el-popover>
          </div>
        </div>
        <a class="bs-g-flabel" @click="showFilter = !showFilter;">
          <span class="cur">筛选</span>
        </a>
      </div>
      <div class="seach-bx has-filter-scroll mobile" :class="{'active':searchIsFocus}">
        <div class="q-f-item-wrap">
          <template v-for="c in cateObj">
            <div class="q-f-item" v-for="s in c.items" v-if="s.selected"><span class="ct">{{ c.name }}</span><span
                class="ct-val">{{ s.title }}</span><i class="it-clr" @click="onParamterClear(c, s)"></i>
            </div>
          </template>
          <input type="text" @focus="searchIsFocus=true" @blur="searchIsFocus=false" v-model="queryParams.title" @keypress.enter="handleSearch"
            :placeholder="'按标题/风格/类型等搜索 ' + inspirationInfo.articleNum + ' 款游戏'" /><a class="cancel-search"
            v-if="queryParams.title" @click="handleXClear"></a>
        </div>
      </div>
    </div> -->
    <div class="list-wrap-flex">
      <ul class="games-data" :class="[model, showFilter ? 'show-filter' : '']">
        <li v-for="(item, idx) in list" :key="idx" class="gd-item" :class="{'no-data':!item.id}">
          <a :href="'/game/' + item.id" target="_blank" v-if="item.id">
            <div class="mimg-box">
              <img loading="lazy" :srcset="item.srcsets" v-lazy="item.lazy" @error="loadError"/>
              <span class="pnum">{{ item.totalImageCount }}</span>
            </div>
            <div class="basic-info">
              <div class="title">{{ item.title }}</div>
              <div class="bot-desc">
                <span class="uname">
                  <img loading="lazy" class="u-img" v-aimgd="{ avatar: item.member.avatar, id: item.member.id, w: 40, name: item.member.userName }"/>
                  <a class="name-text">{{ item.member.userName }}</a>
                  <img loading="lazy" class="u-m-tag" v-for="tag in item.member.tagsList" :src="tag.image" alt="">
                </span>
                <div class="znum">
                  {{ item.praiseStr }}
                </div>
              </div>
            </div>
            <div class="left-icos">
              <!-- <img loading="lazy" src="../../assets/pro/common/hot.png" alt="" v-if="item.hot" /> -->
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover" v-if="item.hot">
                  <i class="sm-tip" slot-content>浏览量超2万的热门内容</i>
                  <img loading="lazy" slot="reference" src="../../assets/pro/common/hot.png" alt="">
              </el-popover>
            <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover" v-if='item.new'>
                <i class="sm-tip" slot-content>48小时内发布的最新内容</i>
                <img loading="lazy" slot="reference" src="../../assets/pro/common/new.png" alt="">
            </el-popover>
              <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover" v-if='item.videoUrl'>
                <i class="sm-tip" slot-content>内容含视频</i>
                <img loading="lazy" slot="reference" src="../../assets/pro/common/video.png" alt="">
              </el-popover>
            </div>
            <div class="right-icos hid-el" v-if="item.tagsList && item.tagsList.length > 0">
              <!-- <img loading="lazy" src="../../assets/pro/common/rz2.png" alt=""> -->
              <img loading="lazy" style="margin-left: 5px" v-for="(t, tdx) in item.tagsList" :key="tdx" :title="t.title" v-if="t.image"
                :src="t.image" alt="" />
            </div>
            <!-- <div class="con-mask hid-el"></div> -->
          </a>
        </li>
        <div class="no-more-text" v-if="!hasMore && !isloading && list.length > 0">没有更多了</div>
        <Empty text="没有找到符合条件的结果~" v-if="!isloading && list.length == 0" />
      </ul>
      <FilterBy  class="sch-sticky" :cates="cateObj" :params="queryParams" ref="refFilterBy" @change="onFilterChange"   viewnumfield="articleNum"
        v-show="showFilter && cateObj.length > 0" />
    </div>
    <div class="pro-bot-loading" v-if="isloading">
      <i class="el-icon-loading"></i>
    </div>

    <el-drawer :with-header="false" destroy-on-close :modal="false" append-to-body :visible.sync="showInfo"
      direction="btt">
      <gameInfo @close="onInfoClose" :id="currentId" />
    </el-drawer>

    <!-- <gameInfo @close="onInfoClose" :id="currentId" v-if="showInfo"/> -->
     <div class="loading-mask" v-if="isloading"></div>
  </div>
</template>

<script>
import Empty from '@/components/Empty'
import FilterBy from '@/components/FilterBy'
import DropDown from '@/components/dropdown'
import pswiper from '@/components/pswiper'
import gameInfo from '@/components/gameInfo'
import api from '@/api/api'
export default {
  components: { gameInfo, pswiper, DropDown, FilterBy, Empty },
  data() {
    return {
      searchIsFocus:false,
      isloading: true,
      inspirationInfo: {
        imageNum: 0,
        content: '',
        articleNum: 0
      },
      showFilter: true,
      cateObj: [],
      tList: [],
      newFilterCates: [],
      tagFilter: [],
      isFocus: false,
      model: 'big',
      currentId: '',
      showInfo: false,
      keyword: '',
      gTypes: [],
      list: [{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}],
      queryParams: {
        pageNum: 1,
        pageSize: 35,
        orderByColumn: 'createTime',
        rank: '首页推荐',
        categoryId: 22,
        isAsc: 'desc',
        categoryIds: '',
        device: ''
      },
      total: 0,
      hasMore: true,
      scrollLoaded: false,
      allCates: [],
      curAllCateKey: '',
      curCates: [],
      curFullPath: ''
    }
  },
  props: ['curgmstyle', 'filterparams', 'filtercates'],
  destroyed() {
    window.removeEventListener('scroll', this.docScroll)
  },
  watch: {
    curgmstyle(newd, old) {
      if (newd) {
        this.queryParams.style = newd;
        this.cateObj[0].items.filter(r => {
          r.selected = false;
          if (r.value == newd) {
            r.selected = true;
          }
        })
      } else {
        this.queryParams.style = '';
        this.cateObj[0].items.filter(r => {
          r.selected = false;
        })
      }
      this.handleSearch();
    },
    keyword(newd, old) {
      this.curCates.map(item => {
        if (item.title.indexOf(newd) > -1) {
          item.show = true;
        } else {
          item.show = false;
        }
      })
    }
  },
  async mounted() {
    $('body,html').animate({ scrollTop: 0 }, 300);
    if (this.filterparams) {
      this.queryParams = Object.assign(this.queryParams, this.filterparams);
    }
    let _k=this.$route.query.k;
    if(_k){
      this.queryParams.title=_k;
    }

    this.queryParams.style = this.curgmstyle;
    // let start=new Date();
    // let starttime=moment(start).format('YYYY-MM-DD');
    // let end=new Date(start.setDate(start.getDate()+1));
    // let endtime=moment(end).format('YYYY-MM-DD')
    // let res=await api.articlelist({orderByColumn:'see',isAsc:'desc',startTime:starttime,endTime:endtime,pageNum:1,pageSize:8})

    let res = await api.getCategoryFilter({ type: 'linggan', subType: 'images' });
    res.data.tags.map(item=>{
        if(item.title=='全部推荐'){
            item.title='全部游戏';
        }
    })
    this.tagFilter = res.data.tags.filter(r=>{
      return r.title!='编辑精选'&&r.title!='普通推荐'
    });
    this.tList = res.data.news;
    res = await api.getInspirationStatis();

    this.curFullPath = this.$route.fullPath;

    // let _gTypes = localStorage.getItem('G-TYPES')
    // _gTypes = JSON.parse(decodeURIComponent(_gTypes))
    // this.gTypes = _gTypes

    let _allCates = JSON.parse(decodeURIComponent(localStorage.getItem('CATE-ALL-TYPES')));
    this.curAllCateKey = _allCates[1].key;
    this.curCates = _allCates[1].result;
    this.allCates = _allCates;

    let _allCateTypes = JSON.parse(decodeURIComponent(localStorage.getItem('OBJ-CATE-ALL-TYPES')));
    let _cdatas = [];
    _cdatas.push({ name: '风格', items: _allCateTypes.styles, queryfield: 'style' })
    _cdatas.push({ name: '类型', items: _allCateTypes.categorys, queryfield: 'categoryIds' })
    _cdatas.push({ name: '主题', items: _allCateTypes.themes, queryfield: 'tags' })
    _cdatas.push({ name: '功能', items: _allCateTypes.funs, queryfield: 'paramImagesDescFunc' })
    _cdatas.push({ name: '材质图案', items: _allCateTypes.materials, queryfield: 'paramImagesDescMaterial' })
    _cdatas.push({ name: '平台', items: _allCateTypes.devices, queryfield: 'device' })
    _cdatas.push({ name: '版式', items: _allCateTypes.orientations, queryfield: 'orientation' })
    _cdatas.push({ name: '上线年份', items: _allCateTypes.eras, queryfield: 'era' })
    _cdatas.map(item => {
      item.items.map(r => {
        r.selected = false;
      })
    })
    if (this.filtercates) {
      _cdatas = Object.assign(_cdatas, this.filtercates);
    }
    let _st = this.$route.query.st;
    if (_st) {
      _cdatas[0].items.map(r => {
        if (r.value == _st) {
          r.selected = true;
        }
      })
    }
    this.cateObj = _cdatas;

    res = await api.getInspirationStatis();
    this.inspirationInfo = res.data;

    this.queryList()
    window.addEventListener('scroll', this.docScroll)
  },
  methods: {
    loadError(e){
        e.target.removeAttribute('srcset');
    },
    docScroll(e) {
      let that = this;
      if (that.showInfo) return
      let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight

      if (that.scrollLoaded == false) return
      if (jHeight <= 200 && that.hasMore) {
        if (!localStorage.getItem('token')) {
          that.$parent.$parent.noLoginIsTak = false;
          that.$parent.$parent.showLoginView = true;
          that.isloading = false;
          window.removeEventListener('scroll', that.docScroll);
          return;
        }

        that.scrollLoaded = false
        that.loadMore()
      }
    },
    onLoaded(e, item) {
      let domainUrl = this.$imgdomainurl + 'article-';
      let el = e.target;
      let _vtime = null;
      if (item.updateTime) {
        _vtime = item.updateTime;
      } else if (item.createTime) {
        _vtime = item.createTime;
      } else if (item.create_time) {
        _vtime = item.create_time.replace('T', ' ');
      }
      _vtime = Math.abs(new Date(_vtime).getTime());
      let srcsets = [];
      srcsets.push(domainUrl + item.id + '-' + _vtime + '@1x432.webp 1x');
      srcsets.push(domainUrl + item.id + '-' + _vtime + '@2x432.webp 2x');
      srcsets.push(domainUrl + item.id + '-' + _vtime + '@3x432.webp 3x');
      el.srcset = srcsets.join(',')
    },
    getimgObj(item) {
      let _vtime = null;
      if (item.updateTime) {
        _vtime = item.updateTime;
      } else if (item.createTime) {
        _vtime = item.createTime;
      } else if (item.create_time) {
        _vtime = item.create_time.replace('T', ' ');
      }
      _vtime = Math.abs(new Date(_vtime).getTime());
      return {
        src: this.$imgdomainurl + 'article-' + item.id + '-' + _vtime + '@1x432.webp',
        error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
        loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
      }
    },
    handleXClear() {
      this.cateObj.map(item => {
        item.items.map(sub => {
          sub.selected = false;
        })
      })
      this.queryParams = {
        pageNum: 1,
        pageSize: 35,
        orderByColumn: 'createTime',
        rank: '首页推荐',
        categoryId: 22,
        isAsc: 'desc',
        categoryIds: '',
        device: ''
      }
      this.handleSearch();
    },
    onParamterClear(parent, sub) {
      this.$refs['refFilterBy'].handleSelSub(parent, sub);
    },
    onFilterChange(_params, _type, _allCate) {
      this.cateObj = _allCate;
      // if (_type == '10') {
      //   this.$emit('changepage', _params, _type, _allCate);
      // } else {
      this.queryParams = _params;
      this.handleSearch();
      // }
    },
    chooseByCate(_item) {
      this.queryParams.categoryIds = _item.value;
      this.queryParams.pageNum = 1;
      this.list = [];
      this.scrollLoaded = false;
      this.hasMore = true;
      this.queryList();
    },
    
    chooseDevice(_device) {
      let that=this;

      let pd=this.cateObj.filter(r=>{
          return r.queryfield=='device';
      })
      let p=pd[0].items.filter(r=>{return r.value==_device});

      this.$refs['refFilterBy'].handleSelSub(pd[0],p[0]);

      // this.cateObj.map(item => {
      //     if (item.queryfield == 'device') {
      //     item.items.map(r => {
      //         r.selected = false;
      //         if (r.value == _device&&that.queryParams.device!=r.value) r.selected = true;
      //     })
      //     }
      // })
      // this.$refs['refFilterBy'].cateObj=this.cateObj;
      // this.$forceUpdate();
      // this.queryParams.device = _device == this.queryParams.device ? '' : _device;
      
      // this.handleSearch();
  },
  chooseScreen(_screen) {
      let pd=this.cateObj.filter(r=>{
          return r.queryfield=='orientation';
      })
      let p=pd[0].items.filter(r=>{return r.value==_screen});

      this.$refs['refFilterBy'].handleSelSub(pd[0],p[0]);

      // let that=this;
      // this.cateObj.map(item => {
      //     if (item.queryfield == 'orientation') {
      //     item.items.map(r => {
      //         r.selected = false;
      //         if (r.value == _screen&&that.queryParams.orientation!=r.value) r.selected = true;
      //     })
      //     }
      // })
      // this.queryParams.orientation = _screen == this.queryParams.orientation ? '' : _screen;

      // this.handleSearch();
      
  },
    handleSearch(e) {
      $('body,html').animate({
        'scrollTop':0
      },200);
      if(e)e.target.blur();
      window.history.pushState({}, 0,e&&e.target.value?('?t=22&k='+e.target.value):'?t=22');
      this.queryParams.pageNum = 1;
      this.list = [];
      this.scrollLoaded = false;
      this.hasMore = true;
      this.queryList();
    },
    onInfoClose() {
      window.history.pushState({}, 0, this.curFullPath);
      document.body.style.overflow = 'inherit';
      this.showInfo = false;
    },
    handleShowInfo(_item) {
      window.history.pushState({}, 0, '/game/' + _item.id);
      this.currentId = _item.id;
      document.body.style.overflow = 'hidden';
      this.showInfo = true;
    },
    loadMore() {
      this.queryParams.pageNum++
      this.queryList()
    },
    async queryList() {
      var that = this

      this.isloading = true;
      // const loading = this.$loading({
      //   lock: true,
      //   text: '努力加载中...',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)'
      // });
      
      if(that.queryParams.pageNum==1){
        that.list=[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}];
      }
      let result = await api.articlelist(that.queryParams);
      if(that.queryParams.pageNum==1){
        that.list=[];
      }
      
      setTimeout(()=>{
        that.isloading = false;
      },300)
      // loading.close();
      
      let old = that.list;
      result.data.map(item=>{
        let _vtime=null;
        if(item.updateTime){
            _vtime=item.updateTime;
        }else if(item.createTime){
            _vtime=item.createTime;
        }else if(item.create_time){
            _vtime=item.create_time.replace('T',' ');
        }
        _vtime=Math.abs(new Date(_vtime).getTime());
        item.lazy = {
            src:that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@1x800.webp',
            error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
            loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
        }
        let srcsets=[];
        srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@1x800.webp 1x');
        srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@2x800.webp 2x');
        srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@3x800.webp 3x');
        item.srcsets=srcsets.join(',')
      })

      that.list = [...old, ...result.data]

      that.total = result.total

      let totalPage = result.total % that.queryParams.pageSize == 0 ? result.total / that.queryParams.pageSize : parseInt(result.total / that.queryParams.pageSize) + 1
      if (result.data && (result.data.length < that.queryParams.pageSize || that.queryParams.pageNum >= totalPage)) {
        that.hasMore = false
      } else {
        that.hasMore = true
      }
      that.scrollLoaded = true
    }
  }
}
</script>

<style lang="less">
.game-list-page {
  min-height:calc(100vh - 84px - 84px - 44px - 64px);
  .sch-sticky{
      top:244px;
  }
  .gp-filter {
    position: sticky;
    top: 169px;
    // z-index:1;
    // margin-top:20px;
    // padding-top:10px;
    // margin-bottom:21px;
    padding-bottom: 21px;
    padding-top:10px;
    margin-bottom: 0px;
    margin-top: 0px;
    display:inline-block !important;
    width:100%;
    .gp-img-layout{
        display: flex;
        align-items: center;
        .q-f-item-wrap{
          display: flex;
          align-items: center;
          // padding-left:10px;
          grid-gap:5px;
        }
    }
    .mobile{
        display: none;
    }
  }
}
</style>